package com.demo.service;

import java.io.File;
import java.io.IOException;
import java.util.Properties;  

import org.python.core.PyFunction;  
import org.python.core.PyInteger;  
import org.python.core.PyObject;  
import org.python.util.PythonInterpreter;  
import java.nio.file.Files;
import java.util.Properties;

/** 
 * Java调用Python代码 
 */  
public class ExecPythonDemo  
{  
    public static void main(String[] args) {  
          
        //Java运行Python文件  
        Properties props = new Properties();  
        props.put("python.console.encoding", "UTF-8");  
        props.put("python.security.respectJavaAccessibility", "false");  
        props.put("python.import.site", "false");  
        Properties preprops = System.getProperties();  
          
        PythonInterpreter.initialize(preprops, props, new String[0]);  
          
        PythonInterpreter interpreter = new PythonInterpreter();    
        interpreter.execfile("D:\\test.py");  
          
          
        //Java调用Python方法  
        PyFunction func = (PyFunction) interpreter.get("test", PyFunction.class);  
        int a = 2016, b = 2;  
        PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));  
        String ret = "a+b = " + pyobj.toString();  
        System.out.println(ret);  
        interpreter.close();  
  
    }  
} 


class PythonDemo {

    public static void main(String[] args) throws IOException {

        //Create interpreter
        Properties props = new Properties();
        props.put("python.home", "path to the Lib folder");
        props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
        props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclasses
        props.put("python.import.site", "false");

        Properties preprops = System.getProperties();

        PythonInterpreter.initialize(preprops, props, new String[0]);
        PythonInterpreter interp = new PythonInterpreter();


        String pythonCodeStr = new String(Files.readAllBytes(new File("test.py").toPath()));
        interp.exec(pythonCodeStr);

    }


}